package com.cf.util;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * cf-game-ObjectJsonService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/3/26 18:02
 */
public class ObjectJsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
    }

    public static <T> T toObject(String content, Class<T> valueType) throws BizException {
        if (StringUtils.isEmpty(content))
            return null;
        try {
            return objectMapper.readValue(content, valueType);
        } catch (IOException e) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "json 序列化错误，content is :【" + (content == null ? "null" : content) + "】type is 【{" + (valueType == null ? "null" : valueType) + "}】", e);
        }
    }

    public static <T> List<T> toListObject(String content, Class<T> valueType) throws BizException {
        if (StringUtils.isEmpty(content))
            return null;
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, valueType);
        try {
            return objectMapper.readValue(content, javaType);
        } catch (IOException e) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "json 序列化错误，content is  :【" + (content == null ? "null" : content) + "】", e);
        }
    }


    public static String toString(Object content) throws BizException {
        try {
            return objectMapper.writeValueAsString(content);
        } catch (JsonProcessingException e) {
            throw new BizException(EnumReturnCode.ERROR.getCode(), "json 序列化错误，content is  :【" + (content == null ? "null" : content) + "】", e);
        }
    }

}
